import React, { useMemo } from 'react';
import { Modal, Form, Input, Select, Upload, Row, Col, TreeSelect, Button, Radio } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { OrganizationItem, SignatureItem } from 'admin/schema/Cas';
import { uploadUrl } from 'admin/servers/servers';
import { useSelector } from 'react-redux';
import { convertToTree, downLoadByUrl } from '../utils';
import { FormInstance } from 'antd/es/form';
import { get } from 'lodash';
import { verifyPhone } from 'utils/tools';

interface Props {
  visible: boolean;
  title: string;
  onOk: () => void;
  onCancel: () => void;
  editingSignature: SignatureItem | null;
  orgTree: Omit<OrganizationItem, 'children' | 'description'>[];
  form: FormInstance;
}

const SignatureFormModal: React.FC<Props> = ({
  visible,
  title,
  onOk,
  onCancel,
  editingSignature,
  orgTree,
  form,
}) => {
  const uniqueToken = useSelector((state: any) => state.uniqueToken);
  const userInfo = useSelector((state: any) => state.loginInfo);

  // 使用 useMemo 缓存树形数据转换结果，避免不必要的重复计算
  const treeData = useMemo(() => {
    const treeData = convertToTree(orgTree);
    return treeData;
  }, [orgTree]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="name"
              label="签名名称"
              rules={[
                { required: true, message: '请输入签名名称' },
                { max: 20, message: '最大长度为20位字符' },
              ]}
            >
              <Input placeholder="请输入签名名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="type" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
              <Select
                placeholder="请选择类型"
                style={{ width: '100%' }}
                disabled={!!editingSignature}
                options={[
                  { label: '行业短信', value: '行业短信' },
                  { label: '靶向短信', value: '靶向短信' },
                ]}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="organizationId"
              label="单位名称"
              rules={[{ required: true, message: '请选择单位' }]}
            >
              <TreeSelect
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择单位"
                fieldNames={{ label: 'name', value: 'id' }}
                allowClear
                treeDefaultExpandAll
                treeData={treeData}
                treeNodeFilterProp="title"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="phone" label="联系电话" rules={verifyPhone}>
              <Input placeholder="请输入联系电话" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="representativeType"
              label="法人类型"
              tooltip="授权委托人必需上传授权书"
              rules={[{ required: true, message: '请选择法人类型' }]}
              initialValue="法定代表人"
            >
              <Radio.Group>
                <Radio value="法定代表人">法定代表人</Radio>
                <Radio value="授权委托人">授权委托人</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="description" label="描述">
              <Input.TextArea rows={1} placeholder="请输入描述" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="idCardFrontImagePath"
              label="身份证国徽面"
              rules={[{ required: true, message: '请上传身份证国徽面照片' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].path'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传身份证国徽面</Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="idCardBackImagePath"
              label="身份证人像面"
              rules={[{ required: true, message: '请上传身份证人像面照片' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].path'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传身份证人像面</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="certificatePath"
              label="社会统一信用代码证（复印件加盖公章电子扫描件）"
              rules={[{ required: true, message: '请上传社会统一信用代码证' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].path'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传社会统一信用代码证</Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="powerOfLetter"
              label="法人或授权委托人免冠证件照电子版"
              rules={[{ required: true, message: '法人或授权委托人免冠证件照电子版' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].path'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传法人或授权委托人免冠证件照电子</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              style={{ marginBottom: 0 }}
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.representativeType !== currentValues.representativeType ||
                prevValues.type !== currentValues.type
              }
            >
              {() => {
                return (
                  <Form.Item
                    name="powerOfAttorney"
                    label="授权书或其他证明材料"
                    rules={[
                      { required: true, message: '请上传签名授权函' },
                      ({ getFieldValue }) => ({
                        required: getFieldValue('representativeType') === '授权委托人',
                        message: '授权委托人必须上传授权书',
                      }),
                    ]}
                    valuePropName="fileList"
                    getValueFromEvent={e => {
                      if (Array.isArray(e)) {
                        return e;
                      }
                      return e && e.fileList;
                    }}
                    extra={
                      <div style={{ display: 'flex', flexDirection: 'column' }}>
                        {form.getFieldValue('type') === '行业短信' && (
                          <>
                            <a href="/webapp/行业-签名授权函.doc" target="_blank">
                              模版-签名授权函.doc
                            </a>
                            <a href="/webapp/行业-授权委托函.docx" target="_blank">
                              模版-授权委托函.docx
                            </a>
                            <a href="/webapp/信息安全承诺书.docx" target="_blank">
                              模版-信息安全承诺书.docx
                            </a>
                          </>
                        )}
                        {form.getFieldValue('type') === '靶向短信' && (
                          <>
                            <a href="/webapp/靶向-签名授权函.doc" target="_blank">
                              模版-签名授权函.doc
                            </a>
                            <a href="/webapp/靶向-授权委托函.docx" target="_blank">
                              模版-授权委托函.docx
                            </a>
                          </>
                        )}
                      </div>
                    }
                  >
                    <Upload
                      name="files"
                      action={uploadUrl}
                      headers={{
                        uniqueToken,
                        userId: userInfo.id,
                      }}
                      showUploadList={{
                        showPreviewIcon: false,
                        showDownloadIcon: true,
                      }}
                      onDownload={(file: any) => {
                        downLoadByUrl(
                          get(file, 'response.data[0].path'),
                          get(file, 'response.data[0].realName')
                        );
                      }}
                    >
                      <Button icon={<UploadOutlined />}>上传授权书或其他证明材料</Button>
                    </Upload>
                  </Form.Item>
                );
              }}
            </Form.Item>
          </Col>
          <Col span={12}>
            <p style={{ fontWeight: 700 }}>
              注意：签名申请运营商审核预计需要7-10个工作日，已报备过短信签名的身份证信息不可再次报备
            </p>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

// 使用 React.memo 优化组件性能，避免不必要的重渲染
export default React.memo(SignatureFormModal);
